<?php

namespace App\Http\Controllers;

use App\Events\addLog;
use App\Models\School;
use App\Models\Student;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ExcelController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * @param Request $request
     * 导出Excel
     */
    public function exportStudent(Request $request)
    {
        $school_id = $request->get('school_id');
        if ($school_id == '0') {
            $school_name = '所有幼儿报名信息';
            event(new addLog(Auth::user(),'导出'.$school_name));
        } else {
            $school_name = School::query()->where('school_code', $school_id)->first()->school_name;
            event(new addLog(Auth::user(),'导出'.$school_name.'报名信息'));
        }
        \Excel::create($school_name, function ($excel) use ($school_id) {
            $student = $this->getStudent($school_id);
            $excel->sheet('报名信息', function ($sheet) use ($student) {
                $sheet->rows($student);
            });
        })->export('xls');

    }


    public function getStudent($school_id)
    {
        $stundentArr = [];
        $stundentArr[] = [
            'StudentName',
            'Sex',
            'IDCode',
            'ZySchoolCode',
            'ZySchoolName',
            'Section',
            'Twins'
        ];
        if ($school_id == '0') {
            $stundents = Student::query()->where('first_kid','=','1')->get();

        } else {
            $stundents = Student::query()->where('school_id', $school_id)
                ->where('first_kid','=','1')->get();
        }
        foreach ($stundents as $key => $value) {
            $school = $value->school;
            $stundentArr[] = [
                $value->name,
                $value->sex,
                " " . $value->id_code,
                $school->school_code,
                $school->school_name,
                $value->section_id,
                $value->twins
            ];
        }
        return $stundentArr;
    }

}
